package com.mall.order.services;

import com.mall.commons.tool.exception.BizException;
import com.mall.order.OrderCoreService;
import com.mall.order.biz.TransOutboundInvoker;
import com.mall.order.biz.context.AbsTransHandlerContext;
import com.mall.order.biz.factory.OrderProcessPipelineFactory;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.constants.OrderConstants;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.OrderShipping;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.OrderShippingMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.*;
import com.mall.order.utils.ExceptionProcessorUtils;
import com.mall.user.constants.SysRetCodeConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 *  ciggar
 * create-date: 2019/7/30-上午10:05
 */
@Slf4j
// 集群容错机制 cluster = "failfast"
@Service
public class OrderCoreServiceImpl implements OrderCoreService {

	@Autowired
	OrderMapper orderMapper;

	@Autowired
	OrderItemMapper orderItemMapper;

	@Autowired
	OrderShippingMapper orderShippingMapper;

	@Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

	@Autowired
	StockMapper stockMapper;
	/**
	 * 创建订单的处理流程
	 *
	 * @param request
	 * @return
	 */
	@Override
	public CreateOrderResponse createOrder(CreateOrderRequest request) {
		CreateOrderResponse response = new CreateOrderResponse();
		try {
			//创建pipeline对象
			TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

			//启动pipeline
			invoker.start(); //启动流程（pipeline来处理）

			//获取处理结果
			AbsTransHandlerContext context = invoker.getContext();

			//把处理结果转换为response
			response = (CreateOrderResponse) context.getConvert().convertCtx2Respond(context);

		} catch (Exception e) {
			log.error("OrderCoreServiceImpl.createOrder Occur Exception :" + e);
			ExceptionProcessorUtils.wrapperHandlerException(response, e);
		}
		return response;
	}



	/**
	 * 根据id取消指定的定单
	 * @param cancelOrderRequest
	 * @return
	 */

	@Override
	public CancelOrderResponse cancelOrder(CancelOrderRequest cancelOrderRequest) {

		CancelOrderResponse cancelOrderResponse = new CancelOrderResponse();
		String orderId = cancelOrderRequest.getOrderId();

		Order order = orderMapper.selectByPrimaryKey(orderId);
		order.setStatus(OrderConstants.ORDER_STATUS_TRANSACTION_CLOSE);
		order.setUpdateTime(new Date());
		orderMapper.updateByPrimaryKey(order);

		Example example = new Example(OrderItem.class);
		example.createCriteria().andEqualTo("orderId",orderId);
		List<OrderItem> orderItems = orderItemMapper.selectByExample(example);

		for (OrderItem orderItem : orderItems) {
			Stock stock = stockMapper.selectStock(orderItem.getItemId());
			long stockCount  = stock.getStockCount() + orderItem.getNum();
			stock.setStockCount(stockCount);
			int lockCount = stock.getLockCount() - orderItem.getNum();
			stock.setLockCount(lockCount);
			stockMapper.updateStock(stock);

			orderItemMapper.updateStockStatus(2, orderId);
		}

		cancelOrderResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
		cancelOrderResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());

		return cancelOrderResponse;
	}

	@Override
	public DeleteOrderResponse deleteOrder(DeleteOrderRequest deleteOrderRequest) {
		DeleteOrderResponse deleteOrderResponse = new DeleteOrderResponse();
		String orderId = deleteOrderRequest.getOrderId();

		//获取该订单信息
		Order order = orderMapper.selectByPrimaryKey(orderId);

		//校验该订单状态
		switch (order.getStatus()) {
			//已付款，未发货，已发货
			case 1:
			case 2:
			case 3: throw new BizException("当前订单尚未完成，无法删除");
				//未付款
			case 0:
				CancelOrderRequest cancelOrderRequest = new CancelOrderRequest();
				cancelOrderRequest.setOrderId(orderId);
				cancelOrder(cancelOrderRequest);
				return deleteOrder(deleteOrderRequest);
			//交易成功，交易关闭，交易失败，已退款
			case 4:
			case 5:
			case 6:
			case 7:
				//先在订单表中将该订单删除
				orderMapper.delete(order);
				//再在订单商品表中将该订单的商品删除
				Example itemExample = new Example(OrderItem.class);
				itemExample.createCriteria().andEqualTo("orderId", orderId);
				orderItemMapper.deleteByExample(itemExample);
				//再在物流信息表中，将该订单的物流信息删除
				Example shippingExample = new Example(OrderShipping.class);
				shippingExample.createCriteria().andEqualTo("orderId", orderId);
				orderShippingMapper.deleteByExample(shippingExample);
		}
		deleteOrderResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
		deleteOrderResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
		return deleteOrderResponse;
	}

}
